import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Add_msg_tim, Msgdel_tim, Send_tim } from '../../TIM/actiontim'
import pxPage from '../../root/pxPage'
import { withRouter } from "react-router-dom"
import './message.css'
import { imgInter } from '../../data/Interface'
import { ActionSheet, Toast } from 'antd-mobile';
import TIM from 'tim-js-sdk';
import COS from 'cos-js-sdk-v5';


const deviceHight = document.documentElement.clientHeight

// 修改滚轮界面随着屏幕大小自适应
//（因为滚轮界面需要一个写死的height才能每次让滚轮滚到最下方）
const scrollStyle = {
    height: pxPage(625),
    backgroundColor: "#080904"
}

const blockStyle = {
    height: pxPage(35)
}

let options = {
    SDKAppID: 1400458473
};
let tim = TIM.create(options);
tim.setLogLevel(1);
tim.registerPlugin({ 'cos-js-sdk': COS });

class C2c2 extends Component {
    constructor(props) {
        super(props)

        this.state = {
            user: this.props.user,
            info: '',
            hasinfo: false,
            message: this.props.message
        }
        localStorage.setItem('trtc', JSON.stringify(this.state.user))
        // console.log(JSON.parse(localStorage.getItem('trtc')))
        this.onChangmessage = this.onChangmessage.bind(this)
        tim.on(TIM.EVENT.MESSAGE_RECEIVED, (event) => {
            // console.log(props);
            props.dispatch(Add_msg_tim(event))
        })
    }

    onChangmessage = (e) => {
        this.setState({ info: e.target.value })
        if (this.state.info != '') {
            this.setState({ hasinfo: true })
        } else {
            this.setState({ hasinfo: false })
        }
    }

    setColor = (hasinfo) => {
        if (hasinfo) {
            return '#c45606'
        } else {
            return '#9546e8'
        }
    }

    scrollToBottom() {
        if (this.messagesEnd) {
            const scrollHeight = this.messagesEnd.scrollHeight;//里面div的实际高度  2000px
            const height = this.messagesEnd.clientHeight;  //网页可见高度  200px
            const maxScrollTop = scrollHeight - height;
            this.messagesEnd.scrollTop = maxScrollTop > 0 ? maxScrollTop : 0;
            //如果实际高度大于可见高度，说明是有滚动条的，则直接把网页被卷去的高度设置为两个div的高度差，实际效果就是滚动到底部了。
        }
    }

    //加键盘回车发送消息的事件
    componentDidMount() {
        document.addEventListener("keydown", this.handleEnterKey);
    }

    componentWillUmount() {
        document.removeEventListener("keydown", this.handleEenterKey);
    }

    handleEnterKey = (e) => {
        if (e.keyCode === 13) {
            if (!this.state.info == '') {
                this.props.dispatch(Send_tim(this.state.user.user_phone, this.state.info))
                this.setState({ info: '' })
            } else {
                console.log('没的消息')
            }
        }
    }

    showActionSheet = () => {
        const BUTTONS = ['视频通话', '音频通话', '取消'];
        ActionSheet.showActionSheetWithOptions({
            options: BUTTONS,
            cancelButtonIndex: BUTTONS.length - 1,
            // destructiveButtonIndex: BUTTONS.length - 2,
            // title: 'title',
            message: '电话',
            maskClosable: true,
        },
            (buttonIndex) => {
                // this.setState({ clicked: BUTTONS[buttonIndex] });
                // console.log(BUTTONS[buttonIndex])
                // this.props.history.push('/')
                if (buttonIndex == 0) {
                    this.props.history.push('/shipin')
                } else if (buttonIndex == 1) {
                    this.props.history.push('/yinpin')
                } else {
                    console.log('取消')
                }
            });
    }

    render() {
        setTimeout(this.scrollToBottom.bind(this), 0)
        // console.log(new Date().toLocaleString())
        const { user, info, hasinfo } = this.state

        const formatDate = (now) => {
            let year = now.getFullYear();  //取得4位数的年份
            let month = now.getMonth() + 1;  //取得日期中的月份，其中0表示1月，11表示12月
            let date = now.getDate() < 10 ? '0' + now.getDate() : now.getDate();      //返回日期月份中的天数（1到31）
            let hour = now.getHours() < 10 ? '0' + now.getHours() : now.getHours();     //返回日期中的小时数（0到23）
            let minute = now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes(); //返回日期中的分钟数（0到59）
            let second = now.getSeconds() < 10 ? '0' + now.getSeconds() : now.getSeconds(); //返回日期中的秒数（0到59）
            return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
        }
        return (
            <div className='c2c' style={{ minHeight: '100vh', display: 'flex', width: '100%' ,backgroundColor:'black'}}>
                <div
                    className='content'
                    ref={(el) => { this.messagesEnd = el; }}
                    style={{ height: deviceHight - `${pxPage(20)}`, }}
                >
                    <div className='c2c-div-top'>
                        <i
                            style={{ position: 'absolute', left: '0.5em', fontSize: '2em' }}
                            className='iconfont icon-fanhui'
                            onClick={() => {
                                // console.log(this.props)
                                this.props.history.goBack()
                                this.props.dispatch(Msgdel_tim())
                            }}
                        ></i>
                        <i
                            style={{ position: 'absolute', right: '3.5em', fontSize: '1.9em' }}
                            className='iconfont icon-weibiaoti-'
                            onClick={
                                () => {
                                    this.showActionSheet()
                                }
                            }
                        ></i>
                        <span style={{ fontWeight: 'bold', fontSize: '1.3em' }}>{user.user_name}</span>
                        <i
                            className='iconfont icon-liebiao1'
                            style={{ position: 'absolute', right: '2em', fontSize: '1.9em' }}
                            onClick={() => {
                                // this.props.history.push('')
                                console.log('路由跳转')
                            }}
                        ></i>
                    </div>
                    {/* 消息上屏 */}
                    {/* 完全没思路 */}
                    <div className="message-div" >
                        {
                            this.props.message.map((item, index) => {
                                // console.log(item)
                                const id = item.ID.split("-")[3]
                                if (id == '1') {
                                    return <div className="c2c2-msg" key={index}>
                                        <img
                                            src={`${imgInter}${((JSON.parse(localStorage.getItem('user')))).business_pic}`}
                                            style={{ borderRadius: '50%', width: '2em', height: '2em', backgroundColor: 'green', marginRight: '10px',objectFit: 'cover' }}></img>
                                        <span>{formatDate(new Date(item.time * 1000))}</span>
                                        {/* <span>{new Date().toLocaleString()}</span> */}
                                        <div className="message-li" key={index} style={{ backgroundColor: '#193276' }}>{item.payload.text}</div>
                                    </div>
                                } else if (id == '0') {
                                    return <div className="c2c2-msg" key={index}>
                                        <img
                                            src={`${imgInter}${user.user_pic}`}
                                            style={{ borderRadius: '50%', width: '2em', height: '2em', backgroundColor: 'green', marginRight: '10px',objectFit: 'cover' }}></img>
                                        <span>{formatDate(new Date(item.time * 1000))}</span>
                                        {/* <span>{new Date().toLocaleString()}</span> */}
                                        <div className="message-li" key={index} style={{ backgroundColor: '#c45606' }}>{item.payload.text}</div>
                                    </div>
                                }

                            })
                        }
                        <div style={{ height: '30px' }}></div>
                    </div>
                    {/* 
                    分左右
                    样式
                    下拉请求

                 */}
                    <div className='c2c-div-bottom'>
                        <input
                            onKeyPress={this.handleEnterKey}
                            className='c2c-getmsg'
                            type='text'
                            value={info}
                            onChange={this.onChangmessage}
                        >
                        </input>
                        <button
                            className='c2c-sendmsg'
                            style={{ backgroundColor: this.setColor(hasinfo) }}
                            onClick={() => {
                                if (!info == '') {
                                    // console.log('发送' + user.user_phone)
                                    this.props.dispatch(Send_tim(user.user_phone, info))
                                    this.setState({ info: '' })
                                } else {
                                    console.log('没的消息')
                                }
                            }}
                        >
                            <i className="iconfont icon-paperplane"></i>
                        </button>
                    </div>
                </div>
                <div style={{ flex: '1' }}></div>
            </div>
        )
    }
}
const mapStateToProps = (state) => ({
    conversation: state.conversation,
    message: state.message
})
export default withRouter(connect(mapStateToProps)(C2c2))